package com.dfy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dfy.dto.SpotDTO;
import com.dfy.entity.Spot;
import com.dfy.entity.UserFavorite;
import com.dfy.mapper.SpotMapper;
import com.dfy.mapper.UserFavoriteMapper;
import com.dfy.service.UserFavoriteService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {

    @Autowired
    private UserFavoriteMapper userFavoriteMapper;
    
    @Autowired
    private SpotMapper spotMapper;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean isFavorite(Long userId, Long spotId) {
        return userFavoriteMapper.selectCount(
            new LambdaQueryWrapper<UserFavorite>()
                .eq(UserFavorite::getUserId, userId)
                .eq(UserFavorite::getSpotId, spotId)
        ) > 0;
    }

    @Override
    @Transactional
    public void addFavorite(Long userId, Long spotId) {
        // 检查是否已收藏
        if (isFavorite(userId, spotId)) {
            return;
        }

        UserFavorite favorite = new UserFavorite();
        favorite.setUserId(userId);
        favorite.setSpotId(spotId);
        favorite.setCreatedAt(LocalDateTime.now());
        favorite.setUpdatedAt(LocalDateTime.now());
        
        userFavoriteMapper.insert(favorite);
    }

    @Override
    @Transactional
    public void removeFavorite(Long userId, Long spotId) {
        userFavoriteMapper.delete(
            new LambdaQueryWrapper<UserFavorite>()
                .eq(UserFavorite::getUserId, userId)
                .eq(UserFavorite::getSpotId, spotId)
        );
    }

    @Override
    public List<SpotDTO> getFavorites(Long userId) {
        log.info("=================== 开始获取用户收藏列表 ===================");
        log.info("用户ID: {}", userId);
        
        // 获取用户收藏的景点ID列表
        List<UserFavorite> favorites = userFavoriteMapper.selectList(
            new LambdaQueryWrapper<UserFavorite>()
                .eq(UserFavorite::getUserId, userId)
        );
        
        log.info("查询到 {} 个收藏记录", favorites.size());
        
        if (favorites.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有收藏的景点ID
        List<Long> spotIds = favorites.stream()
            .map(UserFavorite::getSpotId)
            .collect(Collectors.toList());
        
        log.info("准备查询景点信息，景点IDs: {}", spotIds);
        
        // 使用自定义的查询方法，确保返回所有字段
        List<Spot> spots = spotMapper.selectSpotsByIds(String.join(",", spotIds.stream()
            .map(String::valueOf)
            .collect(Collectors.toList())));
        
        log.info("查询到 {} 个景点信息", spots.size());
        
        // 转换为 DTO
        return spots.stream()
            .map(spot -> {
                SpotDTO dto = new SpotDTO();
                BeanUtils.copyProperties(spot, dto);
                
                // 处理图片URLs
                try {
                    String imageUrls = spot.getImageUrls();
                    log.info("景点 {} 的原始图片数据: {}", spot.getId(), imageUrls);
                    if (StringUtils.hasText(imageUrls)) {
                        if (imageUrls.startsWith("[")) {
                            // 如果是JSON数组格式
                            dto.setImageUrls(objectMapper.readValue(imageUrls, new TypeReference<List<String>>() {}));
                        } else {
                            // 如果是单个URL
                            dto.setImageUrls(Collections.singletonList(imageUrls));
                        }
                        log.info("景点 {} 的图片处理结果: {}", spot.getId(), dto.getImageUrls());
                    } else {
                        dto.setImageUrls(Collections.emptyList());
                        log.info("景点 {} 没有图片数据", spot.getId());
                    }
                } catch (Exception e) {
                    log.error("处理景点 {} 的图片失败: {}", spot.getId(), e.getMessage());
                    dto.setImageUrls(Collections.emptyList());
                }
                
                // 处理标签
                try {
                    String tags = spot.getTags();
                    log.info("景点 {} 的原始标签数据: {}", spot.getId(), tags);
                    if (StringUtils.hasText(tags)) {
                        if (tags.startsWith("[")) {
                            // 如果是JSON数组格式
                            dto.setTags(objectMapper.readValue(tags, new TypeReference<List<String>>() {}));
                        } else {
                            // 如果是逗号分隔的字符串
                            dto.setTags(Arrays.asList(tags.split(",")));
                        }
                        log.info("景点 {} 的标签处理结果: {}", spot.getId(), dto.getTags());
                    } else {
                        dto.setTags(Collections.emptyList());
                        log.info("景点 {} 没有标签数据", spot.getId());
                    }
                } catch (Exception e) {
                    log.error("处理景点 {} 的标签失败: {}", spot.getId(), e.getMessage());
                    dto.setTags(Collections.emptyList());
                }
                
                return dto;
            })
            .collect(Collectors.toList());
    }
} 